package cp.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class Worker implements Runnable {

	private volatile boolean running = false;
	private volatile boolean mainloop = true;
	private volatile int port;
	private volatile Thread tp;
	private Socket client;
	private ServerSocket serverSocket;

	Worker(int port) {
		this.port = port;
		this.tp = new Thread(this);
	}

	public void start() {
		running = true;
		mainloop = true;
		tp.start();
	}

	public void stop() {
		running = false;
		mainloop = false;
	}

	public void run() {
		try {
			while (mainloop) {
				try {
					serverSocket = new java.net.ServerSocket(port);
					System.out.println("Server created " + port);
					client = serverSocket.accept();
					System.out.println("Client connected on Port " + port);
					running = true;
					while (running) {
						System.out.println(leseNachricht(client));
						Thread.sleep(1000);
						writeNachricht(client);

					}

				} catch (StringIndexOutOfBoundsException e) {
					System.out.println("Port: "+ port + " closed");
				} catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally{
					client.close();
					serverSocket.close();					
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	String leseNachricht(java.net.Socket socket) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(socket.getInputStream()));
		char[] buffer = new char[200];
		int anzahlZeichen = bufferedReader.read(buffer, 0, 200); // blockiert
																	// bis
																	// Nachricht
																	// empfangen
		String nachricht = new String(buffer, 0, anzahlZeichen);
		if (nachricht.equals("Debug"))
			running = false;
		return nachricht;
	}

	void writeNachricht(java.net.Socket socket) throws IOException {

		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		out.write(IF.SEND_ACK);
		out.flush(); 
	}
}
